package viewcontroller;

import model.Store;

import com.example.lastprojectbeautiplus.R;
import com.google.gson.Gson;

import adapter.StoreListViewAdapter;
import android.app.Fragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class StoreListViewFragment extends Fragment {
	public StoreListViewFragment() {
	}

	private StoreListViewAdapter lvAdapter;
	private ListView lvStore;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_store_list_view,
				container, false);
		lvStore = (ListView) rootView.findViewById(R.id.lvStore);
		String urlStore = "http://services-beautyplus.rhcloud.com/rest/StoreServices/Stores/";
		new GetStoreList(urlStore).execute();
		return rootView;
	}

	private class GetStoreList extends AsyncTask<Void, Void, Void> {
		private String url;
		private String jsonStore;

		public GetStoreList(String url) {
			this.url = url;
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			utils.ServiceHandler sh = new utils.ServiceHandler();
			// Making a request to url and getting response
			jsonStore = sh.executeGetRequest(url);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			Gson myGson = new Gson();
			final Store[] listStore = myGson.fromJson(jsonStore, Store[].class);
			lvAdapter = new StoreListViewAdapter(getActivity(), listStore);
			lvStore.setAdapter(lvAdapter);
			lvStore.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(getActivity(), SlideMenu.class);
					Bundle storeBundle = new Bundle();
					storeBundle.putInt("StoreID",
							listStore[position].getStoreID());
					storeBundle.putString("StoreName",
							listStore[position].getStoreName());
					intent.putExtra("FromStoreListView", storeBundle);
					getActivity().startActivity(intent);
				}
			});

		}
	}
}
